package com.ge.med.cchelper.popup.job;

import java.util.List;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import com.ge.med.cchelper.Constants;
import com.ge.med.cchelper.bean.Response;
import com.ge.med.cchelper.util.LogUtil;
import com.ge.med.cchelper.util.SSLhelper;
import com.ge.med.cchelper.util.ftp.FTPFactory;
import com.ge.med.cchelper.util.ftp.FtpHelper;

public class UploadVobFileJob extends BaseJob{
	private List<IResource> selectedIFiles;
	public UploadVobFileJob(String message,List<IResource> resources) {
		super(message);
		this.selectedIFiles = resources;
	}

	protected IStatus start(IProgressMonitor arg0) {
		for(IResource selectedIFile:selectedIFiles){
		String noUse = selectedIFile.getFullPath().segment(1);
		String allPath = selectedIFile.getFullPath().toString();
		String realTempPath = allPath.substring(allPath
				.indexOf(noUse) + noUse.length());
		String fileName = selectedIFile.getFullPath()
				.lastSegment();

		String fullPath = selectedIFile.getLocation()
				.toOSString();
		String vobsPath = csession.getVobRoot();
		String remotePath = vobsPath + realTempPath;

		LogUtil.out("upload " + fileName + "...");
		
		FtpHelper ftp = null;
			try {
				ftp = FTPFactory.getConnectionInstance(csession.getHost(), sourceTempDir);
				if(!ftp.uploadFile(fullPath,fileName)){
				   if(FTPFactory.selectionFTPProduce == 2){
					   ftp =  FTPFactory.getConnectionInstance(csession.getHost(), sourceTempDir,1);
				   }else{
					   ftp =  FTPFactory.getConnectionInstance(csession.getHost(), sourceTempDir,2); 
				   }
				   if(ftp.uploadFile(fullPath,fileName)){
					    SSLhelper sslHelper = new SSLhelper(csession);
						Response resdos = sslHelper.execute(Constants.DOS2UNIX+" "+ sourceTempDir + "/"+fileName);
						Response res = sslHelper.executeCT("cp -rf "+ sourceTempDir + "/"+fileName+" " + remotePath);
						int flag = res.getStatus();
						sslHelper.execute("rm -rf "+ sourceTempDir + "/"+ fileName);
						LogUtil.out("upload completed.");
				   }
				}else{
					SSLhelper sslHelper = new SSLhelper(csession);
					Response resdos = sslHelper.execute(Constants.DOS2UNIX+" "+ sourceTempDir + "/"+fileName);
					Response res = sslHelper.executeCT("cp -rf "+ sourceTempDir + "/"+fileName+" " + remotePath);
					int flag = res.getStatus();
					sslHelper.execute("rm -rf "+ sourceTempDir + "/"+ fileName);
					LogUtil.out("upload completed.");
				}
				
			} catch (Exception e) {
				LogUtil.err("Ftp failed." + e.getMessage());
				e.printStackTrace();
				return Status.CANCEL_STATUS;
			}
		}
		return Status.OK_STATUS;
	}

}
